import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

class Message{
    public String from;
    public String to;
    public String words;

    public Message(String from, String to, String words) {
        this.from = from;
        this.to = to;
        this.words = words;
    }
}
@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    private List<Message> messages = new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        //读取messages链表，根据列表的数据，结合网页模板，来构造出一个页面，返回给浏览器
        ServletContext context = getServletContext();
        TemplateEngine engine = (TemplateEngine) context.getAttribute("engine");
        WebContext webContext = new WebContext(req,resp,context);
        webContext.setVariable("messages",messages);
        String html = engine.process("ConfessionWall",webContext);
        resp.getWriter().write(html);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //处理请求内容，把读到的数据解析，得到from、to、words，构造出Message对象，插入到List里面
        String from = req.getParameter("from");
        String to = req.getParameter("to");
        String words = req.getParameter("words");
        messages.add(new Message(from,to,words));
        //重定向到doGet
        resp.sendRedirect("message");
    }
}
